﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Objectware.Silverlight.Testing.Runner.TestResultService;

namespace Objectware.Silverlight.Testing.Runner
{
	public delegate void ResultsEventHandler(TestResultService.TestResult result);

	public class ResultsManager 
	{
		public static readonly ResultsManager Instance = new ResultsManager();
		private static readonly TestResultService.TestResultService TestResultService =
			ServiceLocator.Default.GetInstance<TestResultService.TestResultService>();

		private readonly Dictionary<string, ResultsEventHandler> _subscriptions = 
			new Dictionary<string, ResultsEventHandler>();
		private readonly Dictionary<string, bool> _subscriptionSignaled = 
			new Dictionary<string, bool>();


		private ResultsManager()
		{
			var thread = new Thread(PollThread);
			thread.Start();
		}

		private void PollThread()
		{
			var now = new DateTime(1900,1,1);
			for( ;; )
			{
				var results = TestResultService.GetAllResults();
				foreach( var result in results )
				{
					var key = GetSubscriptionKey(result.Type, result.Method);
					if( this._subscriptions.ContainsKey(key) && !this._subscriptionSignaled[key])
					{
						this._subscriptions[key](result);
					}
				}

				now = DateTime.Now;
				Thread.Sleep(50);
			}
		}


		private static string GetSubscriptionKey(string type, string method)
		{
			return string.Format("{0}+{1}", type, method);
		}

		public void SubscribeToResult(string type, string method, ResultsEventHandler resultsEventHandler)
		{
			var key = GetSubscriptionKey(type, method);
			this._subscriptions[key] = resultsEventHandler;
			this._subscriptionSignaled[key] = false;
		}

		private static void Log(string format, params object[] parameters)
		{
			//File.AppendAllText("c:\\ResultsManager.log", string.Format("{0}\n\r", string.Format(format, parameters)));
		}

	}
}
